<?php
/**
 * crawgroupmembers.php
 * crawuser
 *
 * Created by HyanCat on 15/9/10.
 * Copyright (C) 2015 HyanCat. All rights reserved.
 */

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/QQGroup.php';
require_once __DIR__ . '/config.php';

ORM::configure('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname']);
ORM::configure('username', $config['db']['username']);
ORM::configure('password', $config['db']['password']);
ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4'));

kvlog();
foreach ($config['users'] as $aUser) {
	kvlog('User', $aUser['uin']);
	$qqGroup = new QQGroup($aUser['uin'], $aUser['skey']);
	// 如果设置了群号列表，则只抓取这些群成员
	if (array_key_exists('groups', $aUser) && count($aUser['groups']) > 0) {
		foreach (array_unique($aUser['groups']) as $gid) {
			crawGroupMembers($qqGroup, $gid);
		}
	}
	// 如果没用设置群号列表，则抓取该用户的所有群的群成员
	else {
		$groups = $qqGroup->getUsersGroups();
		foreach ($groups as $aGroup) {
			crawGroupMembers($qqGroup, $aGroup['gid']);
		}
	}
}

function getUsersGroups(QQGroup $group)
{
	$group->getUsersGroups();
}

function crawGroupMembers(QQGroup $group, $gid)
{
	kvlog('Begin', $gid);
	$members = $group->getGroupMembers($gid);
	if (count($members) > 0) {
		foreach ($members as $aMember) {
			if (false === checkUser($aMember['qq'])) {
				saveUser($group->getUin(), $gid, $aMember['qq'], $aMember['name']);
				kvlog('Save', $aMember['qq']);
			}
		}
	}
	else {
		kvlog('Error', $gid);
	}
}

function checkUser($qq)
{
	global $config;
	$findUser = ORM::for_table($config['db']['table'])->where('qq', $qq)->find_one();

	return $findUser;
}

function saveUser($uin, $gid, $qq, $name)
{
	global $config;
	$newUser       = ORM::for_table($config['db']['table'])->create();
	$newUser->uin  = $uin;
	$newUser->gid  = $gid;
	$newUser->qq   = $qq;
	$newUser->name = $name;
	$newUser->save();
}

function kvlog($key = null, $value = null)
{
	if (is_null($key)) {
		echo PHP_EOL;

		return;
	}
	date_default_timezone_set("Asia/Shanghai");
	echo date('[Y-m-d h:i:s]') . ' ';
	if (is_null($value)) {
		echo $key . PHP_EOL;
	}
	else {
		echo '[' . $key . "]: " . $value . PHP_EOL;
	}
}
